<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Models\Comment;
use App\Models\Cookbook;
use App\Models\Notebook;
use App\Models\Star;
use App\Models\User;
use App\Services\NotifyService;
use Illuminate\Http\Request;

class StarController extends BaseController
{

    public $model = Star::class;

    /**
     * 评论
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Throwable
     */
    public function store(Request $request) {
        $this->validate($request, [
            'entity_id' => 'required',
            'type' => 'required|in:1,2'
        ]);
        $user = $this->getUser();
        $input = $request->input();

        return \DB::transaction(function () use($input, $user){
            if ($input['type'] == Comment::TYPE_COOKBOOK) {
                $entity_model = new Cookbook();
            } else {
                $entity_model = new Notebook();
            }
            $entity_result = $entity_model->find($input['entity_id']);
            if (!$entity_result)
                return $this->failed("ID对应数据不存在");

            $input['user_id'] = $user->id;
            if ($input['type'] == Comment::TYPE_COOKBOOK) {
                $input['entity_user_id'] = $entity_result->merchant_id;
            } else {
                $input['entity_user_id'] = $entity_result->user_id;
            }

            $one = (new $this->model)->where('user_id', $user->id)->where('entity_id', $input['entity_id'])
                ->where('type', $input['type'])->first();
            if ($one) {
                $one->delete();
                $star = 'cancel';
            } else {
                $this->model::create($input);
                $star = 'ok';
                if ($input['type'] == Comment::TYPE_NOTEBOOK)
                    NotifyService::store($input['user_id'], 1, $input['entity_id'], $input['entity_user_id']);
            }
            $num = ($star == 'ok' ? 1 : -1);
            if ($input['type'] == Comment::TYPE_COOKBOOK) {
                $user->increment('collect_cookbook_count', $num);
            } else {
                //当前用户自己点赞数增减
                $user->increment('star_count', $num);
                //被点赞用户 点赞数增减
                $stared = User::find($input['entity_user_id']);
                $stared->increment('stared_count', $num);
            }
            $entity_result->star_num = $entity_result->star_num + $num;
            $entity_result->save();

            return $this->success([
                'star' => $star
            ]);
        });
    }

}

